<template>
    <div class="markdown">
        <el-form ref="form" :model="markdownData" label-width="80px">
            <template  v-if="isSelect">
                <el-form-item label="文章类型">
                    <el-select v-model="markdownData.type" placeholder="请选择">
                        <el-option
                            v-for="item in options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
            </template>
            <template v-if="markdownData.type === 'news'">
                <el-form-item label="新闻分类">
                    <el-select v-model="markdownData.category" placeholder="请选择">
                        <el-option
                            v-for="item in categoryOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
            </template>
            <el-form-item label="文章名称">
                <el-input v-model="markdownData.name" size="small" style="width: 400px;"></el-input>
            </el-form-item>
            <el-form-item label="文章描述">
                <el-input type="textarea" size="small" v-model="markdownData.description"></el-input>
            </el-form-item>
            <el-form-item class="submit" style="text-align: center;">
                <mavon-editor v-model="content" ref="md"  @imgAdd="$imgAdd" @change="change" style="min-height: 600px"/>
                <el-button type="primary" v-if="isSelect" @click="submitAdd">保存</el-button>
                <el-button type="primary" v-else  @click="submitEdit">更新</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import { strEncodeOrDecode, imageType } from '../utils/mUtils'
import { mavonEditor } from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'

export default {
    components: {
        mavonEditor
    },
    data() {
         return {
            category: false,
            isSelect: true,
            imgType:  '',
            imageUrl: '',
            content: '',
            markdownData: {
                name: "",
                type: "",
                content: '123',
                category: ""
            },
            options: [
                {
                    label: '开发服务',
                    value: 'devServe'
                },
                {
                    label: '新闻',
                    value: 'news'
                },
            ],
            categoryOptions: [
                {
                    label: '最新活动',
                    value: 'activity'
                },
                {
                    label: '公司资讯',
                    value: 'information'
                },
                {
                    label: '公司动态',
                    value: 'trends'
                },
            ]
         }
    },

    methods: {
         // 将图片上传到服务器，返回地址替换到md中
        $imgAdd(pos, $file){
            var formdata = new FormData();
            formdata.append('file', $file);
            // 这里没有服务器供大家尝试，可将下面上传接口替换为你自己的服务器接口
            this.$axios({
                url: '/api/upload',
                method: 'post',
                data: formdata,
                headers: { 'Content-Type': 'multipart/form-data' },
            }).then((res) => {
                this.$refs.md.$img2Url(pos, process.env.VUE_APP_IMG + res.data.filename);
            })
        },
        getDetail() {
            // @ts-ignore
            const id = this.$route.query.id
            const type = this.$route.query.type
            this.category = this.$route.query.category

            if (id) {
                this.isSelect = false
                this.$axios(`/api/${type}/id/` + id).then(res => {
                    if (res.data)  {
                        this.markdownData = res.data.result
                        this.id = res.data.result.id
                        // 解码 decode
                        this.content = strEncodeOrDecode(res.data.result.content, 'decode')
                    }
                })
            }
        },

        handleAvatarSuccess(res, file) {
            this.imageUrl = URL.createObjectURL(file.raw);
            this.markdownData.desc_img = res.data.name
        },
        beforeAvatarUpload(file) {
            const isIMG = imageType(file.type);
            const isLt2M = file.size / 1024 / 1024 < 2;

            this.imgType = isIMG
            if (!isIMG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isIMG && isLt2M;
        },

        change(content, render) {
            this.content = content
        },

        submitAdd() {
            this.deleteCategory()
            // 编码 encode
            this.markdownData.content = strEncodeOrDecode(this.content, 'encode')
            this.$axios.post(`/api/${this.markdownData.type}/add`, this.markdownData).then(res => {
                if (res.data.errno === 0) {
                     this.$message({
                        message: res.data.msg,
                        type: "success"
                    })
                    return
                }
                this.$message(res.data.msg)
            })
        },

        submitEdit() {
            this.deleteCategory()
            // 编码 encode
            this.markdownData.content = strEncodeOrDecode(this.content, 'encode')
            this.$axios.post(`/api/${this.markdownData.type}/update/${this.$route.query.id}`, this.markdownData).then(res => {
                if (res.data.errno === 0) {
                     this.$message({
                        message: res.data.msg,
                        type: "success"
                    })
                    return
                }
                this.$message(res.data.msg)
            })
        },
        deleteCategory () {
            if (this.markdownData.type !== 'news') {
                this.category = false
                delete this.markdownData.category
            }
        }

    },

     mounted() {
         this.getDetail()
     }
    
}
</script> 


<style lang="less" scoped>
.markdown {
    margin: 20px 50px;
}
.my-editor {
    height: 5rem;
    border: 1px solid #999;
}
.submit {
    .el-button {
        text-align: center;
        margin-top: 20px;
    }
}
</style>